import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Request,
  Query,
  ParseIntPipe,
  ForbiddenException,
} from '@nestjs/common';
import { VideoService } from './video.service';
import { ApiOperation, ApiParam, ApiQuery, ApiResponse } from '@nestjs/swagger';
import { Public } from 'src/common/decorators/public';
import { CreateVideoDto } from './dto/create-video.dto';
import { GetUserVideosDto, VideoStatusFilter } from './dto/get-user-videos.dto';
import { UpdateVideoDto } from './dto/update-video.dto';
import { ToggleVideoVisibilityDto } from './dto/toggle-video-visibility.dto';
import { ResubmitVideoDto } from './dto/resubmit-video.dto';
import { QueryVideosDto } from './dto/query-videos.dto';
import { RejectVideoDto } from './dto/reject-video.dto';

@Controller('video')
export class VideoController {
  constructor(private readonly videoService: VideoService) {}

  /**
   * @description 获取OSS上传凭证
   */
  @Get('getToken')
  @Public()
  @ApiOperation({ summary: '获取OSS上传凭证' })
  findAll() {
    return this.videoService.generateUploadToken();
  }

  /**
   * @description 高级分页查询视频
   */
  @Get('query')
  @ApiOperation({ summary: '高级分页查询视频' })
  @ApiResponse({
    status: 200,
    description: '查询成功',
  })
  async queryVideos(@Query() queryDto: QueryVideosDto) {
    return this.videoService.queryVideos(queryDto);
  }

  /**
   * @description 发布视频
   */
  @Post('publish')
  @ApiOperation({ summary: '发布视频' })
  publishVideo(@Body() createVideoDto: CreateVideoDto, @Request() req) {
    return this.videoService.createVideo(createVideoDto, req.user.id);
  }

  /**
   * @description 随机获取视频
   */
  @Get('random')
  @Public()
  @ApiOperation({ summary: '随机获取指定数量的视频' })
  @ApiQuery({
    name: 'count',
    required: false,
    description: '需要获取的视频数量，默认为5',
    type: Number,
  })
  @ApiResponse({
    status: 200,
    description: '随机获取视频成功',
  })
  async getRandomVideos(@Query('count') count: number = 5, @Request() req) {
    const currentUserId = req.user?.id;
    return this.videoService.getRandomVideos(count, currentUserId);
  }

  /**
   * @description 视频审核回调
   */
  @Get('censorCallBack')
  @Public()
  @ApiOperation({ summary: '视频审核回调' })
  videoCallback(@Request() req) {
    console.log('视频审核回调', req.body);
    return this.videoService.updateVideoStatus(req.body);
  }

  /**
   * 获取单个视频的详细信息
  */
  @Get(':id')
  @Public()
  @ApiOperation({ summary: '获取单个视频的详细信息' })
  @ApiParam({ name: 'id', description: '视频ID' })
  @ApiResponse({
    status: 200,
    description: '获取视频详情成功',
  })
  async getVideoDetails(@Param('id', ParseIntPipe) id: number, @Request() req) {
    const currentUserId = req.user?.id;
    return this.videoService.getVideoDetails(id, currentUserId);
  }

  /**
   * @description 删除视频
   */
  @Delete('deleteVideo/:id')
  @ApiOperation({ summary: '根据id删除视频' })
  remove(@Param('id') id: string) {
    return this.videoService.remove(+id);
  }

  /**
   * @description 获取用户的视频列表
   */
  @Get('user/:userId/videos')
  @ApiOperation({ summary: '获取用户的视频列表' })
  @ApiParam({ name: 'userId', description: '用户ID' })
  @ApiResponse({
    status: 200,
    description: '获取视频列表成功',
  })
  async getUserVideos(
    @Param('userId', ParseIntPipe) userId: number,
    @Query() query: GetUserVideosDto,
    @Request() req,
  ) {
    const currentUserId = req.user?.id;
    return this.videoService.getUserVideos(userId, currentUserId, query);
  }

  /**
   * 获取用户的公开视频列表
   */
  @Get('user/:userId/public-videos')
  @Public() // 可以设置为公开接口
  @ApiOperation({ summary: '获取用户的公开视频列表' })
  @ApiParam({ name: 'userId', description: '用户ID' })
  @ApiResponse({ status: 200, description: '获取成功' })
  async getUserPublicVideos(
    @Param('userId', ParseIntPipe) userId: number,
    @Query('page') page: number = 1,
    @Query('limit') limit: number = 10,
    @Request() req,
  ) {
    const currentUserId = req.user?.id;
    return this.videoService.getUserPublicVideos(
      userId,
      currentUserId,
      page,
      limit,
    );
  }

  /**
   * @description 获取当前登录用户的视频列表
   */
  @Get('my/videos')
  @ApiOperation({ summary: '获取当前登录用户的视频列表' })
  @ApiQuery({
    name: 'keyword',
    required: false,
    description: '搜索关键词（搜索标题或分类名称）',
  })
  @ApiQuery({
    name: 'status',
    required: false,
    enum: VideoStatusFilter,
    description: '视频状态筛选',
  })
  async getMyVideos(@Query() query: GetUserVideosDto, @Request() req) {
    const currentUserId = req.user.id;
    return this.videoService.getUserVideos(currentUserId, currentUserId, query);
  }

  /**
   * @description 更新视频信息
   */
  @Patch(':id')
  @ApiOperation({ summary: '更新视频信息（标题、描述、分类）' })
  @ApiParam({ name: 'id', description: '视频ID' })
  @ApiResponse({ status: 200, description: '更新成功' })
  async updateVideo(
    @Param('id', ParseIntPipe) id: number,
    @Body() updateVideoDto: UpdateVideoDto,
    @Request() req,
  ) {
    const userId = req.user.id;
    return this.videoService.updateVideo(id, updateVideoDto, userId);
  }

  /**
   * @description 管理员更新视频信息
   */
  @Patch('admin/:id')
  @ApiOperation({ summary: '管理员更新视频信息' })
  @ApiParam({ name: 'id', description: '视频ID' })
  @ApiResponse({ status: 200, description: '更新成功' })
  async adminUpdateVideo(
    @Param('id', ParseIntPipe) id: number,
    @Body() updateVideoDto: UpdateVideoDto,
  ) {
    return this.videoService.adminUpdateVideo(id, updateVideoDto);
  }

  /**
   * @description 切换视频可见性（公开/隐藏）
   */
  @Patch(':id/visibility')
  @ApiOperation({ summary: '切换视频可见性（公开/隐藏）' })
  @ApiParam({ name: 'id', description: '视频ID' })
  @ApiResponse({ status: 200, description: '更新成功' })
  async toggleVideoVisibility(
    @Param('id', ParseIntPipe) id: number,
    @Body() toggleVisibilityDto: ToggleVideoVisibilityDto,
    @Request() req,
  ) {
    const userId = req.user.id;
    return this.videoService.toggleVideoVisibility(
      id,
      toggleVisibilityDto.isPublic,
      userId,
    );
  }

  /**
   * @description 重新提交审核不通过的视频
   */
  @Post(':id/resubmit')
  @ApiOperation({ summary: '重新提交审核不通过的视频' })
  @ApiParam({ name: 'id', description: '视频ID' })
  @ApiResponse({ status: 200, description: '重新提交成功' })
  async resubmitVideo(
    @Param('id', ParseIntPipe) id: number,
    @Body() resubmitVideoDto: ResubmitVideoDto,
    @Request() req,
  ) {
    const userId = req.user.id;
    return this.videoService.resubmitVideo(id, resubmitVideoDto, userId);
  }

  /**
   * @description 管理员下架视频（将approved或manualReview状态改为rejected）
   */
  @Patch('admin/:id/reject')
  @ApiOperation({ summary: '管理员下架视频' })
  @ApiParam({ name: 'id', description: '视频ID' })
  @ApiResponse({ status: 200, description: '下架成功' })
  async rejectVideo(
    @Param('id', ParseIntPipe) id: number,
    @Body() rejectVideoDto: RejectVideoDto,
  ) {
    return this.videoService.rejectVideo(id, rejectVideoDto.reason);
  }

  /**
   * @description 管理员审核通过视频（将manualReview状态改为approved）
   */
  @Patch('admin/:id/approve')
  @ApiOperation({ summary: '管理员审核通过视频' })
  @ApiParam({ name: 'id', description: '视频ID' })
  @ApiResponse({ status: 200, description: '审核通过成功' })
  async approveVideo(@Param('id', ParseIntPipe) id: number) {
    return this.videoService.approveVideo(id);
  }
}
